﻿#include "plan_list_item_widget.h"
#include "ui_plan_list_item_widget.h"
#include <QFile>

PlanListItemWidget::PlanListItemWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlanListItemWidget),
    m_timer(new QTimer)
{
    ui->setupUi(this);
    initUi();

    initEvents();
}

PlanListItemWidget::~PlanListItemWidget()
{
    delete ui;
}

QString PlanListItemWidget::text()
{
    return ui->textEdit->toPlainText();
}

void PlanListItemWidget::setText(QString text)
{
    disconnect(ui->textEdit, &QTextEdit::textChanged, this, &PlanListItemWidget::onTextChanged);
    ui->textEdit->setText(text);
    emit(heightChanged(ui->textEdit->fontMetrics().lineSpacing() * ui->textEdit->document()->lineCount() + 46));
    connect(ui->textEdit, &QTextEdit::textChanged, this, &PlanListItemWidget::onTextChanged);
}

void PlanListItemWidget::setUuid(const QString &uuid)
{
    m_uuid = uuid;
}

QString PlanListItemWidget::getUuid() const
{
    return m_uuid;
}

QSize PlanListItemWidget::size()
{
    int externHeight = ui->frame->isVisible() ? ui->frame->height() : 0;
    return QSize(this->width(),
                 ui->textEdit->fontMetrics().lineSpacing() *
                 ui->textEdit->document()->lineCount() +
                 externHeight + 20);
}

void PlanListItemWidget::initUi()
{
    ui->frame->hide();
    setAttribute(Qt::WA_StyledBackground);
    // 定制样式
#ifdef Q_OS_ANDROID
    QFile styleFile(":/resources/qss/plan_list_item_widget_android.qss");
#else
    QFile styleFile(":/resources/qss/plan_list_item_widget.qss");
#endif
    styleFile.open(QIODevice::ReadOnly);
    QString stylesheet = styleFile.readAll();
    styleFile.close();

    setStyleSheet(stylesheet);
}

void PlanListItemWidget::initEvents()
{
    m_timer->setInterval(1000);
    connect(ui->textEdit, &QTextEdit::textChanged, this, &PlanListItemWidget::onTextChanged);

    connect(m_timer, &QTimer::timeout, this, [=]() {
        emit(textChanged(this));
        m_timer->stop();
    });

    connect(ui->menuBtn, &QPushButton::clicked, this, [=]() {
        emit(menuTriggered(this));
    });
}

void PlanListItemWidget::onTextChanged()
{
    if (!m_timer->isActive()) {
        m_timer->start();
    } else {
        m_timer->stop();
        m_timer->start();
    }

    emit(heightChanged(size().height()));
}

